import os
import pdb

import MSSafeinsideLib as lib
c = lib.MSConfig.getConfig()
l = lib.log

## PATTERN FUNCTIONS TO DISPLAY PAGE ##
class Common:
    ready   = False
    head    = None
    foot    = None
    topbarAnon  = None
    topbarUser  = None

    @staticmethod
    def checkReady():
        if Common.ready: return
        f = open(c.get('main', 'html') + 'head.html', 'r')
        Common.head = [f.read()]
        f = open(c.get('main', 'html') + 'foot.html', 'r')
        Common.foot = [f.read()]
        f = open(c.get('main', 'html') + 'topbar_anonymous.html', 'r')
        Common.topbarAnon = [f.read()]
        f = open(c.get('main', 'html') + 'topbar_loggeduser.html', 'r')
        Common.topbarUser = [f.read()]
        Common.ready = True

    @staticmethod
    def putHeader(functor, status, contentinfo):
        #contentinfo = [(<mimetype>,<content>), ...]
        statuses =  {
                    200: '200 OK',
                    400: '400 Bad Request',
                    404: '404 Not Found',
                    }
        s = statuses.get(status, statuses[400])
        content = []
        for info in contentinfo:
            if info[0] == 'Set-Cookie': content += [('Set-Cookie', info[1])]
            else:   content += [('Content-Type', info[1] + '/' + info[0])]
        functor(s, content)
    @staticmethod
    def get404(functor, name):
        Common.putHeader(functor, 404, [('html', 'text')])
        return ['<h3>page ' + name + ' not found</h3>']
    @staticmethod
    def getHead():
        Common.checkReady()
        return Common.head
    @staticmethod
    def getFoot(): 
        Common.checkReady()
        return Common.foot
    @staticmethod
    def getTopbar():
        Common.checkReady()
        return Common.topbarAnon
# OBJECT PATTERNS #

class PatternTable:
    def __init__(self, classname=None, idname=None, bodyname=None):
        self.classname  = classname
        self.idname     = idname
        self.bodyname   = bodyname

    def open(self, meta):
        tag =   '<table '
        if self.classname:   tag += 'class="%s" ' % str(self.classname)
        if self.idname:      tag += 'id="%s" ' % str(self.idname)
        tag +=  '>'
        tag +=  '<thead><tr>'
        columnCount = 0
        for name, desc in meta:
            c =     '<th '
            for propname, propval in desc.iteritems():
                c += '%s="%s" ' % (str(propname), str(propval))
            c +=    '>' + str(name) + '</th>'
            tag += c
            columnCount += 1
        self.columnCount = columnCount
        tag +=  '</tr></thead>'
        tag +=  '<tbody '
        if self.bodyname: tag += 'class="%s" id="%s"' % (str(self.bodyname), str(self.bodyname))
        tag +=  '>'
        return [tag]
    def close(self):
        tag = '</tbody></table>'
        return [tag]
    def add(self, e):
        tag =   '<tr>'
        for i in range(0, self.columnCount): tag += '<th>' + str(e[i]) + '</th>'
        tag +=  '</tr>'
        return [tag]

class PatternElement:
    def __init__(self, name, etype, desc):
        self.name = name
        self.desc = desc
        self.etype = etype

    def open(self, meta, value='', closetag=False, hidden=False):
        tag = '<div class="clearfix" '
        if hidden: tag += 'hidden="true" '
        tag += '>'
        tag += '<label for="%s">%s</label>' % (self.name, self.desc)
        tag += '<div class="%s">' % self.etype
        tag += '<%s ' % self.etype
        for pname, pval in meta.iteritems():
            tag += '%s="%s"' % (str(pname), str(pval))
        tag += '>'
        if closetag: tag += value + '</%s>' % self.etype
        tag += '</div>'
        tag += '</div>'
        return [tag]

class PatternElement:
    def __init__(self, name, etype, desc):
        self.name = name
        self.desc = desc
        self.etype = etype
        self.helpmsg = ''

    def setHelpInline(self, msg): self.helpmsg = msg

    def open(self, meta, value='', closetag=False, hidden=False):
        tag = '<div class="clearfix" '
        if hidden: tag += 'hidden="true" '
        tag += '>'
        tag += '<label for="%s">%s</label>' % (self.name, self.desc)
        tag += '<div class="%s">' % self.etype
        tag += '<%s ' % self.etype
        for pname, pval in meta.iteritems():
            tag += '%s="%s"' % (str(pname), str(pval))
        tag += '>'
        if closetag: tag += value + '</%s>' % self.etype
        if len(self.helpmsg) > 0: tag += '<span class="help-inline">' + self.helpmsg + '</span>'
        tag += '</div>'
        tag += '</div>'
        return [tag]


class PatternForm:
    def __init__(self, action, button, method):
        self.action = '/method/' + action
        self.method = method
        self.target = '_blank'
        self.button = button

    def open(self, meta, extra=''):
        tag =   '<form action=%s target=%s method=%s>' % (self.action, self.target, self.method)
        for k, v in meta.iteritems():
            t = PatternElement(k, v['type'], v['desc'])
            tag += t.open(v['meta'], v['value'], v['closetag'], v['hidden'])[0]

        tag += extra
        tag +=  '<button class="btn primary" type="submit">%s</button>' % self.button
        tag +=  '</form>'
        return [tag]


## PATTERN FUNCTIONS TO HANDLE USER DATA ##
def checkName(name):
    if name and type(name) == type(str()) and len(name) >= 1 and name.find('..') == -1: return True
    return False
def checkFile(name):
    if os.path.exists(name): return True
    return False
